package com.sunday.fangbeibei.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.http.Header;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.adapter.ImageBrowseAdapter;
import com.sunday.fangbeibei.orm.HouseImage;
import com.sunday.fangbeibei.orm.ImageInfo;
import com.sunday.fangbeibei.orm.LayoutImageInfo;

/**
 * 

* @ClassName: ImageBrowseActivity 

* @Description: TODO(图片浏览activity) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年1月26日 上午10:30:57 

*
 */
public class ImageBrowseActivity extends BaseActivity implements OnClickListener,OnPageChangeListener{

	private ViewPager viewPager;
	private TextView title;
	private TextView number;
	
	private int[] normalImages={R.drawable.icon1,R.drawable.icon2,R.drawable.icon3,R.drawable.icon4,R.drawable.icon5,R.drawable.icon6,R.drawable.icon7,R.drawable.icon8};;
	private int[] selectImages={R.drawable.icon1_s,R.drawable.icon2_s,R.drawable.icon3_s,R.drawable.icon4_s,R.drawable.icon5_s,R.drawable.icon6_s,R.drawable.icon7_s,R.drawable.icon8_s};;
	private View[] menus;
	
	private ImageBrowseAdapter adapter;
	
	private int position;
	private List<HouseImage> lists;
	
	private List<ImageInfo> images;
	
	
	@Override
	protected void createActivity(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// 设置标题栏无
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.image_browse_layout);
		boolean flag=getIntent().getBooleanExtra("flag", false);
		if(!flag){
			position=getIntent().getIntExtra("position", 0);
			lists=(List<HouseImage>) getIntent().getSerializableExtra("images");
			menus=new View[lists.size()];
			loadView();
			loadData(position);
			loadMenu(position);
		}else{
			loadView();
			HorizontalScrollView hs=(HorizontalScrollView) findViewById(R.id.bottom);
			hs.setVisibility(View.INVISIBLE);
			LinearLayout bottomll=(LinearLayout) findViewById(R.id.bottomll);
			bottomll.setBackgroundColor(getResources().getColor(R.id.write));
			
			LinearLayout layoutimage=(LinearLayout) findViewById(R.id.layoutimage);
			layoutimage.setVisibility(View.VISIBLE);
			TextView name=(TextView) findViewById(R.id.name);
			TextView content=(TextView) findViewById(R.id.content);
			LayoutImageInfo result=(LayoutImageInfo) getIntent().getSerializableExtra("images");
			title.setText("户型图");
			if(result!=null){
				name.setText(result.getName());
				content.setText(result.getContent());
				images=result.getImages();
				adapter=new ImageBrowseAdapter(this, images);
				viewPager.setAdapter(adapter);
				number.setText(viewPager.getCurrentItem()+1+"/"+adapter.getCount());
			}
		}
	}
	
	private void loadView(){
		
		viewPager=(ViewPager) findViewById(R.id.viewpager);
		viewPager.setOnPageChangeListener(this);
		
		title=(TextView) findViewById(R.id.title);
		number=(TextView) findViewById(R.id.number);
		
		if(!getIntent().getBooleanExtra("flag", false)){
			title.setText(lists.get(position).getName());
			
			LinearLayout bottom=(LinearLayout) findViewById(R.id.bottomll);
			
			
			for(int i=0;i<lists.size();i++){
				View v=LayoutInflater.from(mContext).inflate(R.layout.browse_menu, null);
				v.setLayoutParams(new LayoutParams(this.getWindowManager().getDefaultDisplay().getWidth()/4, LayoutParams.WRAP_CONTENT));
				
				TextView name=(TextView) v.findViewById(R.id.name);
				name.setText(lists.get(i).getName());
				
				int type=Integer.valueOf(lists.get(i).getType())-1;
				if(type>7){
					type=7;
				}
				
				int[] image={normalImages[type],selectImages[type],i};
				
				menus[i]=v;
				
				v.setTag(image);
				v.setOnClickListener(this);
				
				bottom.addView(v);
			}
			
		}
		
		ImageView close=(ImageView) findViewById(R.id.close);
		ImageView download=(ImageView) findViewById(R.id.download);
		
		OnClickListener listener=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch(v.getId()){
				case R.id.close:
					finish();
					break;
				case R.id.download:
					if(images!=null&&images.size()>0){
						ImageInfo info=images.get(viewPager.getCurrentItem());
						try {
							downloadFile(info);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}		
					break;
				}
			}
		};
		
		close.setOnClickListener(listener);
		download.setOnClickListener(listener);
		
		
	}
	
	private void loadMenu(int pos){
		
		for(int i=0;i<lists.size();i++){
			View v=menus[i];
			
			int[] tag=(int[]) v.getTag();
			
			ImageView image=(ImageView) v.findViewById(R.id.image);
			TextView name=(TextView) v.findViewById(R.id.name);
			if(i==pos){
				image.setImageDrawable(mContext.getResources().getDrawable(tag[1]));
				name.setTextColor(mContext.getResources().getColor(R.color.orange));
				
				v.setFocusable(true);//可以在xml中配置

				v.setFocusableInTouchMode(true);//可以在xml中配置
				
				v.requestFocus();
				
			}else{
				image.setImageDrawable(mContext.getResources().getDrawable(tag[0]));
				name.setTextColor(mContext.getResources().getColor(R.color.white));
			}
			
			
		}
		
	}
	
	
	private void loadData(int pos){
		
		//String[] array={"drawable://"+R.drawable.effects_1,"drawable://"+R.drawable.effects_2,"drawable://"+R.drawable.effects_3,"drawable://"+R.drawable.effects_4};
		
		images=lists.get(pos).getAtts();
		
		adapter=new ImageBrowseAdapter(this, images);
		viewPager.setAdapter(adapter);
		number.setText(viewPager.getCurrentItem()+1+"/"+adapter.getCount());
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int[] tag=(int[]) v.getTag();
		loadMenu(tag[2]);
		loadData(tag[2]);
		title.setText(lists.get(tag[2]).getName());
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		number.setText(viewPager.getCurrentItem()+1+"/"+adapter.getCount());
	}

	@Override
	public void onPageSelected(int arg0) {
		// TODO Auto-generated method stub
		
	}
	
		
	 /**
	 * @param url
	 * @throws Exception
	 */
	 public void downloadFile(final ImageInfo info) throws Exception {
	
		if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
			Toast.makeText(mContext, "您的手机不存在存储卡！", Toast.LENGTH_SHORT).show();
			return;
		}
		
		show("正在下载,请稍后");
		 
		String url=info.getPath(); 
		 
		AsyncHttpClient client = new AsyncHttpClient();
		// 指定文件类型
		String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
		// 获取二进制数据如图片和其他文件
		client.get(url, new BinaryHttpResponseHandler(allowedContentTypes) {
	
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] binaryData) {
				
				File direct=new File(Environment.getExternalStorageDirectory().getPath() +"/fbb");
				if(!direct.exists()){
					direct.mkdir();
				}
				
				String path = Environment.getExternalStorageDirectory()
						.getPath() +"/fbb/"+ info.getFileName();
				Bitmap bmp = BitmapFactory.decodeByteArray(binaryData, 0,
						binaryData.length);
	
				File file = new File(path);
				// 压缩格式
				CompressFormat format = Bitmap.CompressFormat.JPEG;
				// 压缩比例
				int quality = 100;
				try {
					// 若存在则删除
					if (file.exists())
						file.delete();
					// 创建文件
					file.createNewFile();
					//
					OutputStream stream = new FileOutputStream(file);
					// 压缩输出
					bmp.compress(format, quality, stream);
					// 关闭
					stream.close();
					
					disMiss();
					Toast.makeText(mContext, "图片下载成功！", Toast.LENGTH_SHORT).show();
	
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					disMiss();
					Toast.makeText(mContext, "图片下载失败！", Toast.LENGTH_SHORT).show();
				}
	
			}
	
			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] binaryData, Throwable error) {
				// TODO Auto-generated method stub
				disMiss();
				Toast.makeText(mContext, "图片下载失败！", Toast.LENGTH_SHORT).show();
			}
	
	
			@Override
			public void onRetry(int retryNo) {
				// TODO Auto-generated method stub
				super.onRetry(retryNo);
			}
	
		});
	}
		

}
